"""Datastore utility class"""
import cgi
import urllib2;

from google.appengine.ext import db
from google.appengine.api import images

import entities
from util.constants import DATA_TYPE_IMAGE as IMAGE
from util.constants import DATA_TYPE_URL as URL
from util.constants import DATA_TYPE_PHONE_NO as PHONE_NO
from util.constants import DATA_TYPE_PLAIN_TXT as PLAIN_TXT
from util.errors import InvalidUrlParamException
from util.errors import UnknownClientException

def check_exists_by_key_name(entity, key_name):
	try:
		d = entity.get_by_key_name(key_name)

		if d:
			return True
	except Exception:
		return False
		
def save_data(r_sender_key_name, r_owner_key_name, r_data_type, r_data):
	
	if not check_exists_by_key_name(entities.Device, r_sender_key_name):
		raise UnknownClientException('Unknown client type')

	if r_data_type == PLAIN_TXT:
		# Phone numbers and plain text are sent as the same thing from
		# clients, but saved differently on server.
		# Determine if the data is a phone number using regular expression
		# search and treat as such.
		
		from util.constants import RE_PHONE_NO_PATTERN as PHONE_PATTERN
		# If RE search finds a match in the data:
		if PHONE_PATTERN.search(r_data):
			data = entities.ExchangedData(data_type=PHONE_NO, \
				data_owner=entities.Device.get_by_key_name(r_owner_key_name), \
				data_sender=entities.Device.get_by_key_name(r_sender_key_name))

			data.data_content = db.PhoneNumber(r_data)
		else:
			data = entities.ExchangedData(data_type=PLAIN_TXT, \
				data_owner=entities.Device.get_by_key_name(r_owner_key_name), \
				data_sender=entities.Device.get_by_key_name(r_sender_key_name))

			# Save string as Unicode
			data.data_content = cgi.escape(unicode(r_data))
	elif r_data_type == IMAGE:
		data = entities.ExchangedData(data_type=IMAGE, \
				data_owner=entities.Device.get_by_key_name(r_owner_key_name), \
				data_sender=entities.Device.get_by_key_name(r_sender_key_name))

		image_data = images.Image(r_data)
			
		# And just for the hell of it...
		image_data.im_feeling_lucky()
		# Actually, it's because I wanted to transform it to PNG.
		# You can't call the below without doing an actual transform.
		image_data.execute_transforms(output_encoding=images.PNG)
			
		data.data_content = db.Blob(image_data)
	elif r_data_type == URL:
		data = entities.ExchangedData(data_type=URL, \
				data_owner=entities.Device.get_by_key_name(r_owner_key_name), \
				data_sender=entities.Device.get_by_key_name(r_sender_key_name))
		# Decode the gibberish encoded URL	
		data.data_content = db.Link(urllib2.unquote(r_data))
	else:
		raise InvalidUrlParamException('Unknown data type')
			
	# Return the key of the newly saved data
	return data.put()
